<template>
    <div>
        <h4 style="color:deepskyblue;">屠宰信息&ensp;&ensp;<el-button @click="SlaughterdialogVisible = true">设置</el-button>
        </h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="批次：">{{ form.productionLot }}</el-descriptions-item>
            <el-descriptions-item label="到厂均重：">{{ form.weightToFactory }}</el-descriptions-item>
            <el-descriptions-item label="到厂时间：">{{ form.arrivaldateTime }}</el-descriptions-item>
            <el-descriptions-item label="屠宰时间：">{{ form.slaughterdateTime }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:deepskyblue;">相关资质</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="fileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :before-upload="beforeAvatarUpload" :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove" :on-success="handleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4 style="color:deepskyblue;">企业信息&ensp;&ensp;<el-button @click="Corporationaddtion">设置</el-button></h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="公司名称：">{{ form1.companyName }}</el-descriptions-item>
            <el-descriptions-item label="成立时间：">{{ form1.establishmentDateTime }}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions column="1">
            <el-descriptions-item label="公司地址：">{{ codeToText[form1.province] }}&nbsp;{{ codeToText[form1.city]
                }}&nbsp;{{
                    codeToText[form1.county] }}</el-descriptions-item>
            <el-descriptions-item label="公司简介：">{{ form1.companyProfile }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:deepskyblue;">企业照片</h4>
        <br />
        <el-upload v-model:file-list="fileList1" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview1" :on-remove="handleRemove1"
            :before-upload="beforeAvatarUpload1" :on-success="handleAvatarSuccess1">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>

        <!-- 屠宰弹框 -->
        <el-dialog v-model="SlaughterdialogVisible" title="屠宰信息" width="800">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="批次：">
                            <el-input v-model="form.productionLot" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="到厂均重：" prop="weightToFactory">
                            <el-input v-model="form.weightToFactory" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="到厂时间：" prop="arrivalTime">
                            <el-date-picker v-model="form.arrivalTime" type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="屠宰时间" prop="slaughterTime">
                            <el-date-picker v-model="form.slaughterTime" type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 公司弹框 -->
        <el-dialog v-model="CorporationdialogVisible" title="公司信息" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form1" :rules="rules1" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="公司名称：" prop="companyName">
                    <el-input v-model="form1.companyName" />
                </el-form-item>
                <el-form-item label="公司地址：" prop="">
                    <el-cascader size="large" :options="options" v-model="form1.address" @change="handleChange"
                        style="width: 100%;" clearable />
                </el-form-item>
                <el-form-item label="成立时间：" prop="establishmentTime">
                    <el-date-picker v-model="form1.establishmentTime" type="date" placeholder="请输入出栏日期"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="公司简介" prop="companyProfile">
                    <el-input v-model="form1.companyProfile" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="CorporationsubmitForm(ruleFormRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile, FormInstance, FormRules } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'

import http from '@/http'
const route = useRoute()

//批次号
const productionLotId = sessionStorage.getItem('productionLot')

//屠宰信息弹框
const SlaughterdialogVisible = ref(false)
//公司信息弹框值
const CorporationdialogVisible = ref(false)

//屠宰数据
const form = reactive({
    "sId": 0,
    "productionLot": productionLotId,
    "weightToFactory": "",
    "arrivalTime": "",
    "slaughterTime": "",
    "relevantQualification": "",
    "slaughteringCompanyId": 0,
    "slaughterdateTime": "",
    "arrivaldateTime": ""
})

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
//屠宰的正则验证
const rules = reactive<FormRules>({
    weightToFactory: [
        { required: true, message: '请输入到厂均重', trigger: 'blur' },
        { pattern: /^([1-9][0-9]*)+(.[0-9]{1,2})?$/, message: '请输入合法数字或1~2位的小数', trigger: 'blur' },
    ],
    arrivalTime: [
        {
            required: true,
            message: '请输入到厂时间',
            trigger: 'change',
        },
    ],
    slaughterTime: [
        {
            required: true,
            message: '请输入屠宰时间',
            trigger: 'change',
        },
    ],
})

//添加公司信息弹框
const Corporationaddtion = () => {
    CorporationdialogVisible.value = true
}

//公司数据
const form1 = reactive({
    "cId": 0,
    "productionLot": productionLotId,
    "companyName": "",
    "province": '',
    "city": '',
    "county": '',
    "address": [] as Array<string>,
    "establishmentTime": "",
    "companyPicture": "",
    "establishmentDateTime": "",
    "companyProfile": "",
})

const options = ref(regionData)

const handleChange = () => {
    if (
        form1.address[0] != null &&
        form1.address[1] != null &&
        form1.address[2] != null
    ) {
        const str =
            codeToText[form1.address[0]] +
            '/' +
            codeToText[form1.address[1]] +
            '/' +
            codeToText[form1.address[2]]
    }
}

//回显公司数据
const getCorporationInfo = () => {
    http.get(`/api/Slaughter/GetCorporationInfo?productionLot=${productionLotId}&slaughteringCompanyId=${form.slaughteringCompanyId}`).then(res => {
        let d = res.data

        form1.cId = d.cId
        form1.companyName = d.companyName
        form1.province = d.province
        form1.city = d.city
        form1.county = d.county
        form1.address.push(form1.province.toString())
        form1.address.push(form1.city.toString())
        form1.address.push(form1.county.toString())
        form1.establishmentTime = d.establishmentTime
        form1.establishmentDateTime = d.establishmentDateTime
        form1.companyPicture = d.companyPicture
        form1.companyProfile = d.companyProfile
    })
}

//公司的正则验证
const rules1 = reactive<FormRules>({
    companyName: [
        { required: true, message: '请输入养殖场', trigger: 'blur' },
    ],
    headOfBreeding: [
        { required: true, message: '请输入负责人', trigger: 'blur' },
    ],
    breedingQuantity: [
        { required: true, message: '请输入存栏数量', trigger: 'blur' },
    ],
})

//添加屠宰信息
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (form.sId == 0 || form.sId == undefined) {

                http.post('/api/Slaughter/AddSlaughter', form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        SlaughterdialogVisible.value = false
                        GetSlaughterInfo()
                    } else {
                        ElMessage.error('保存失败')
                    }
                })
            } else {
                http.put('/api/Slaughter/UpdateSlaughter', form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        SlaughterdialogVisible.value = false
                        GetSlaughterInfo()
                    } else {
                        ElMessage.error('保存失败')
                    }
                })
            }
        } else {
        }
    })
}

//添加公司信息
const CorporationsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            form1.province = form1.address[0]
            form1.city = form1.address[1]
            form1.county = form1.address[2]

            if (form1.cId == 0 || form1.cId == undefined) {
                http.post('/api/Slaughter/AddCorporation', form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        CorporationdialogVisible.value = false
                        GetSlaughterInfo()
                        getCorporationInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            } else {
                http.put('/api/Slaughter/UpdateCorporation', form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        CorporationdialogVisible.value = false
                        GetSlaughterInfo()
                        getCorporationInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            }
        } else {
        }
    })
}

//屠宰
const fileList = ref<UploadUserFile[]>([])

// 相关资质判重
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (fileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}


//删除相关资质
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    handUpLoad(fileList)
}

//放大图片
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

//动检证上传
const handleAvatarSuccess = (data: any) => {
    handUpLoad(fileList)
}

const handUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        productionLot: productionLotId,
        urlImg: str,
    }

    http.post('/api/Slaughter/BatchSlaughterPicList', info).then(res => {
        if (res.data > 0) {
            GetSlaughterInfo()
        }
    })
}

//显示相关资质图片
const getPicList = () => {
    http.get('/api/Slaughter/GetSlaughterPicture?productionLot=' + productionLotId).then(res => {
        if (res.data == null) return
        fileList.value = res.data
    })
}

//显示屠宰信息
const GetSlaughterInfo = () => {
    http.get('/api/Slaughter/GetSlaughterInfo?productionLot=' + productionLotId).then(res => {
        let d = res.data

        form.sId = d.sId
        form.slaughteringCompanyId = d.slaughteringCompanyId
        form.arrivalTime = d.arrivalTime
        form.relevantQualification = d.relevantQualification
        form.slaughterTime = d.slaughterTime
        form.weightToFactory = d.weightToFactory == 0 ? null : d.weightToFactory
        form.slaughterdateTime = d.slaughterDateTime
        form.arrivaldateTime = d.arrivalDateTime
        getCorporationInfo()
        getPicList1()
    })
}


//公司图片
const fileList1 = ref<UploadUserFile[]>([])

//公司
const dialogImageUrl1 = ref('')
const dialogVisible1 = ref(false)
const handlePictureCardPreview1: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl1.value = uploadFile.url!
    dialogVisible1.value = true
}

// 公司图片判重
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
    if (fileList1.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//删除公司图片
const handleRemove1: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    handUpLoad1(fileList1)
}

//显示公司图片
const getPicList1 = () => {
    http.get(`/api/Slaughter/GetCorporationPicture?productionLot=${productionLotId}&slaughteringCompanyId=${form.slaughteringCompanyId}`).then(res => {
        if (res.data == null) {
            return
        }
        fileList1.value = res.data
    })
}

//公司图片上传
const handleAvatarSuccess1 = (data: any) => {
    handUpLoad1(fileList1)
}

const handUpLoad1 = (list: any) => {
    let str = ''
    console.log(list)
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        productionLot: productionLotId,
        urlImg: str,
        sId: form.slaughteringCompanyId
    }


    http.post('/api/Slaughter/BatchCorporationPicList', info).then(res => {
        if (res.data > 0) {
            GetSlaughterInfo()
        }
    })
}

//钩子函数
onMounted(() => {
    GetSlaughterInfo()
    getPicList()
})
</script>

<style scoped></style>